#!/sbin/openrc-run
# shellcheck shell=ksh

depend() {
  after vtunnel-peer
  after network-online
}

GUESTAGENT_LOGFILE="${GUESTAGENT_LOGFILE:-${LOG_DIR:-/var/log}/${RC_SVCNAME}.log}"

supervisor=supervise-daemon
name="Rancher Desktop Guest Agent"
command=/usr/local/bin/rancher-desktop-guestagent
command_args="
  ${GUESTAGENT_ADMIN_INSTALL:+-adminInstall=${GUESTAGENT_ADMIN_INSTALL}}
  ${GUESTAGENT_KUBERNETES:+-kubernetes=${GUESTAGENT_KUBERNETES}}
  ${GUESTAGENT_IPTABLES:+-iptables=${GUESTAGENT_IPTABLES}}
  ${GUESTAGENT_PRIVILEGED_SERVICE:+-privilegedService=${GUESTAGENT_PRIVILEGED_SERVICE}}
  ${GUESTAGENT_DOCKER:+-docker=${GUESTAGENT_DOCKER}}
  ${GUESTAGENT_CONTAINERD:+-containerd=${GUESTAGENT_CONTAINERD}}
  ${GUESTAGENT_K8S_SVC_ADDR:+-k8sServiceListenerAddr=${GUESTAGENT_K8S_SVC_ADDR}}
  ${GUESTAGENT_DEBUG:+-debug}
  "
command_args="${command_args//$'\n'/ }"
output_log="'${GUESTAGENT_LOGFILE}'"
error_log="'${GUESTAGENT_LOGFILE}'"

respawn_delay=5
respawn_max=0

start_pre() {
  cat > /etc/logrotate.d/guestagent <<EOF
  ${GUESTAGENT_LOGFILE} {
    missingok
    notifempty
  }
EOF
}

# shellcheck disable=SC2163
if [ -f /etc/environment ]; then
    while read -r line; do
        # pam_env implementation:
        # - '#' is treated the same as newline; terminates value
        # - skip leading tabs and spaces
        # - skip leading "export " prefix (only single space)
        # - skip leading quote ('\'' or '"') on the value side
        # - skip trailing quote only if leading quote has been skipped;
        #   quotes don't need to match; trailing quote may be omitted
        line="$(echo "$line" | sed -E "s/^[ \\t]*(export )?//; s/#.*//; s/(^[^=]+=)[\"'](.*[^\"'])?[\"']?$/\1\2/")"
        if [ -n "$line" ]; then
          export "$line"
        fi
    done </etc/environment
fi
